package com.sc.portal.service.impl;

import com.sc.common.pojo.CommonResult;
import com.sc.common.utils.CookieUtils;
import com.sc.common.utils.HttpClientUtil;
import com.sc.common.utils.JsonUtils;
import com.sc.pojo.TbUser;
import com.sc.portal.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther sc
 * @Date 2017/11/5
 */
@Service
public class UserServiceImpl implements UserService {

    @Value("${SSO_BASE_URL}")
    private String SSO_BASE_URL;

    @Override
    public TbUser getUserByToken(HttpServletRequest request, HttpServletResponse response) {
        try {
            //cookie中去token
            String token = CookieUtils.getCookieValue(request, "user_token");
            if(StringUtils.isBlank(token)){
                return null;
            }
            //调用sso服务查询用户
            String json = HttpClientUtil.doGet(SSO_BASE_URL + "/user/token/" + token);
            CommonResult result = CommonResult.format(json);
            if(result.getStatus()!=200){
                return null;
            }
            //用户对象
            CommonResult result1 = CommonResult.formatToPojo(json, TbUser.class);
            TbUser user = (TbUser) result1.getData();
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
